home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pdb.py < prev    next >
Text File  |  2009-11-02  |  45KB  |  1,307 lines

  1. #! /usr/bin/python2.6
  2.  
  3. """A Python debugger."""
  4.  
  5. # (See pdb.doc for documentation.)
  6.  
  7. import sys
  8. import linecache
  9. import cmd
  10. import bdb
  11. from repr import Repr
  12. import os
  13. import re
  14. import pprint
  15. import traceback
  16.  
  17.  
  18. class Restart(Exception):
  19.     """Causes a debugger to be restarted for the debugged python program."""
  20.     pass
  21.  
  22. # Create a custom safe Repr instance and increase its maxstring.
  23. # The default of 30 truncates error messages too easily.
  24. _repr = Repr()
  25. _repr.maxstring = 200
  26. _saferepr = _repr.repr
  27.  
  28. __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
  29.            "post_mortem", "help"]
  30.  
  31. def find_function(funcname, filename):
  32.     cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
  33.     try:
  34.         fp = open(filename)
  35.     except IOError:
  36.         return None
  37.     # consumer of this info expects the first line to be 1
  38.     lineno = 1
  39.     answer = None
  40.     while 1:
  41.         line = fp.readline()
  42.         if line == '':
  43.             break
  44.         if cre.match(line):
  45.             answer = funcname, filename, lineno
  46.             break
  47.         lineno = lineno + 1
  48.     fp.close()
  49.     return answer
  50.  
  51.  
  52. # Interaction prompt line will separate file and call info from code
  53. # text using value of line_prefix string.  A newline and arrow may
  54. # be to your liking.  You can set it once pdb is imported using the
  55. # command "pdb.line_prefix = '\n% '".
  56. # line_prefix = ': '    # Use this to get the old situation back
  57. line_prefix = '\n-> '   # Probably a better default
  58.  
  59. class Pdb(bdb.Bdb, cmd.Cmd):
  60.  
  61.     def __init__(self, completekey='tab', stdin=None, stdout=None):
  62.         bdb.Bdb.__init__(self)
  63.         cmd.Cmd.__init__(self, completekey, stdin, stdout)
  64.         if stdout:
  65.             self.use_rawinput = 0
  66.         self.prompt = '(Pdb) '
  67.         self.aliases = {}
  68.         self.mainpyfile = ''
  69.         self._wait_for_mainpyfile = 0
  70.         # Try to load readline if it exists
  71.         try:
  72.             import readline
  73.         except ImportError:
  74.             pass
  75.  
  76.         # Read $HOME/.pdbrc and ./.pdbrc
  77.         self.rcLines = []
  78.         if 'HOME' in os.environ:
  79.             envHome = os.environ['HOME']
  80.             try:
  81.                 rcFile = open(os.path.join(envHome, ".pdbrc"))
  82.             except IOError:
  83.                 pass
  84.             else:
  85.                 for line in rcFile.readlines():
  86.                     self.rcLines.append(line)
  87.                 rcFile.close()
  88.         try:
  89.             rcFile = open(".pdbrc")
  90.         except IOError:
  91.             pass
  92.         else:
  93.             for line in rcFile.readlines():
  94.                 self.rcLines.append(line)
  95.             rcFile.close()
  96.  
  97.         self.commands = {} # associates a command list to breakpoint numbers
  98.         self.commands_doprompt = {} # for each bp num, tells if the prompt must be disp. after execing the cmd list
  99.         self.commands_silent = {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list
  100.         self.commands_defining = False # True while in the process of defining a command list
  101.         self.commands_bnum = None # The breakpoint number for which we are defining a list
  102.  
  103.     def reset(self):
  104.         bdb.Bdb.reset(self)
  105.         self.forget()
  106.  
  107.     def forget(self):
  108.         self.lineno = None
  109.         self.stack = []
  110.         self.curindex = 0
  111.         self.curframe = None
  112.  
  113.     def setup(self, f, t):
  114.         self.forget()
  115.         self.stack, self.curindex = self.get_stack(f, t)
  116.         self.curframe = self.stack[self.curindex][0]
  117.         self.execRcLines()
  118.  
  119.     # Can be executed earlier than 'setup' if desired
  120.     def execRcLines(self):
  121.         if self.rcLines:
  122.             # Make local copy because of recursion
  123.             rcLines = self.rcLines
  124.             # executed only once
  125.             self.rcLines = []
  126.             for line in rcLines:
  127.                 line = line[:-1]
  128.                 if len(line) > 0 and line[0] != '#':
  129.                     self.onecmd(line)
  130.  
  131.     # Override Bdb methods
  132.  
  133.     def user_call(self, frame, argument_list):
  134.         """This method is called when there is the remote possibility
  135.         that we ever need to stop in this function."""
  136.         if self._wait_for_mainpyfile:
  137.             return
  138.         if self.stop_here(frame):
  139.             print >>self.stdout, '--Call--'
  140.             self.interaction(frame, None)
  141.  
  142.     def user_line(self, frame):
  143.         """This function is called when we stop or break at this line."""
  144.         if self._wait_for_mainpyfile:
  145.             if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
  146.                 or frame.f_lineno<= 0):
  147.                 return
  148.             self._wait_for_mainpyfile = 0
  149.         if self.bp_commands(frame):
  150.             self.interaction(frame, None)
  151.  
  152.     def bp_commands(self,frame):
  153.         """ Call every command that was set for the current active breakpoint (if there is one)
  154.         Returns True if the normal interaction function must be called, False otherwise """
  155.         #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit
  156.         if getattr(self,"currentbp",False) and self.currentbp in self.commands:
  157.             currentbp = self.currentbp
  158.             self.currentbp = 0
  159.             lastcmd_back = self.lastcmd
  160.             self.setup(frame, None)
  161.             for line in self.commands[currentbp]:
  162.                 self.onecmd(line)
  163.             self.lastcmd = lastcmd_back
  164.             if not self.commands_silent[currentbp]:
  165.                 self.print_stack_entry(self.stack[self.curindex])
  166.             if self.commands_doprompt[currentbp]:
  167.                 self.cmdloop()
  168.             self.forget()
  169.             return
  170.         return 1
  171.  
  172.     def user_return(self, frame, return_value):
  173.         """This function is called when a return trap is set here."""
  174.         frame.f_locals['__return__'] = return_value
  175.         print >>self.stdout, '--Return--'
  176.         self.interaction(frame, None)
  177.  
  178.     def user_exception(self, frame, exc_info):
  179.         exc_type, exc_value, exc_traceback = exc_info
  180.         """This function is called if an exception occurs,
  181.         but only if we are to stop at or just below this level."""
  182.         frame.f_locals['__exception__'] = exc_type, exc_value
  183.         if type(exc_type) == type(''):
  184.             exc_type_name = exc_type
  185.         else: exc_type_name = exc_type.__name__
  186.         print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
  187.         self.interaction(frame, exc_traceback)
  188.  
  189.     # General interaction function
  190.  
  191.     def interaction(self, frame, traceback):
  192.         self.setup(frame, traceback)
  193.         self.print_stack_entry(self.stack[self.curindex])
  194.         self.cmdloop()
  195.         self.forget()
  196.  
  197.     def displayhook(self, obj):
  198.         """Custom displayhook for the exec in default(), which prevents
  199.         assignment of the _ variable in the builtins.
  200.         """
  201.         print repr(obj)
  202.  
  203.     def default(self, line):
  204.         if line[:1] == '!': line = line[1:]
  205.         locals = self.curframe.f_locals
  206.         globals = self.curframe.f_globals
  207.         try:
  208.             code = compile(line + '\n', '<stdin>', 'single')
  209.             save_stdout = sys.stdout
  210.             save_stdin = sys.stdin
  211.             save_displayhook = sys.displayhook
  212.             try:
  213.                 sys.stdin = self.stdin
  214.                 sys.stdout = self.stdout
  215.                 sys.displayhook = self.displayhook
  216.                 exec code in globals, locals
  217.             finally:
  218.                 sys.stdout = save_stdout
  219.                 sys.stdin = save_stdin
  220.                 sys.displayhook = save_displayhook
  221.         except:
  222.             t, v = sys.exc_info()[:2]
  223.             if type(t) == type(''):
  224.                 exc_type_name = t
  225.             else: exc_type_name = t.__name__
  226.             print >>self.stdout, '***', exc_type_name + ':', v
  227.  
  228.     def precmd(self, line):
  229.         """Handle alias expansion and ';;' separator."""
  230.         if not line.strip():
  231.             return line
  232.         args = line.split()
  233.         while args[0] in self.aliases:
  234.             line = self.aliases[args[0]]
  235.             ii = 1
  236.             for tmpArg in args[1:]:
  237.                 line = line.replace("%" + str(ii),
  238.                                       tmpArg)
  239.                 ii = ii + 1
  240.             line = line.replace("%*", ' '.join(args[1:]))
  241.             args = line.split()
  242.         # split into ';;' separated commands
  243.         # unless it's an alias command
  244.         if args[0] != 'alias':
  245.             marker = line.find(';;')
  246.             if marker >= 0:
  247.                 # queue up everything after marker
  248.                 next = line[marker+2:].lstrip()
  249.                 self.cmdqueue.append(next)
  250.                 line = line[:marker].rstrip()
  251.         return line
  252.  
  253.     def onecmd(self, line):
  254.         """Interpret the argument as though it had been typed in response
  255.         to the prompt.
  256.  
  257.         Checks whether this line is typed at the normal prompt or in
  258.         a breakpoint command list definition.
  259.         """
  260.         if not self.commands_defining:
  261.             return cmd.Cmd.onecmd(self, line)
  262.         else:
  263.             return self.handle_command_def(line)
  264.  
  265.     def handle_command_def(self,line):
  266.         """ Handles one command line during command list definition. """
  267.         cmd, arg, line = self.parseline(line)
  268.         if cmd == 'silent':
  269.             self.commands_silent[self.commands_bnum] = True
  270.             return # continue to handle other cmd def in the cmd list
  271.         elif cmd == 'end':
  272.             self.cmdqueue = []
  273.             return 1 # end of cmd list
  274.         cmdlist = self.commands[self.commands_bnum]
  275.         if (arg):
  276.             cmdlist.append(cmd+' '+arg)
  277.         else:
  278.             cmdlist.append(cmd)
  279.         # Determine if we must stop
  280.         try:
  281.             func = getattr(self, 'do_' + cmd)
  282.         except AttributeError:
  283.             func = self.default
  284.         if func.func_name in self.commands_resuming : # one of the resuming commands.
  285.             self.commands_doprompt[self.commands_bnum] = False
  286.             self.cmdqueue = []
  287.             return 1
  288.         return
  289.  
  290.     # Command definitions, called by cmdloop()
  291.     # The argument is the remaining string on the command line
  292.     # Return true to exit from the command loop
  293.  
  294.     do_h = cmd.Cmd.do_help
  295.  
  296.     def do_commands(self, arg):
  297.         """Defines a list of commands associated to a breakpoint
  298.         Those commands will be executed whenever the breakpoint causes the program to stop execution."""
  299.         if not arg:
  300.             bnum = len(bdb.Breakpoint.bpbynumber)-1
  301.         else:
  302.             try:
  303.                 bnum = int(arg)
  304.             except:
  305.                 print >>self.stdout, "Usage : commands [bnum]\n        ...\n        end"
  306.                 return
  307.         self.commands_bnum = bnum
  308.         self.commands[bnum] = []
  309.         self.commands_doprompt[bnum] = True
  310.         self.commands_silent[bnum] = False
  311.         prompt_back = self.prompt
  312.         self.prompt = '(com) '
  313.         self.commands_defining = True
  314.         self.cmdloop()
  315.         self.commands_defining = False
  316.         self.prompt = prompt_back
  317.  
  318.     def do_break(self, arg, temporary = 0):
  319.         # break [ ([filename:]lineno | function) [, "condition"] ]
  320.         if not arg:
  321.             if self.breaks:  # There's at least one
  322.                 print >>self.stdout, "Num Type         Disp Enb   Where"
  323.                 for bp in bdb.Breakpoint.bpbynumber:
  324.                     if bp:
  325.                         bp.bpprint(self.stdout)
  326.             return
  327.         # parse arguments; comma has lowest precedence
  328.         # and cannot occur in filename
  329.         filename = None
  330.         lineno = None
  331.         cond = None
  332.         comma = arg.find(',')
  333.         if comma > 0:
  334.             # parse stuff after comma: "condition"
  335.             cond = arg[comma+1:].lstrip()
  336.             arg = arg[:comma].rstrip()
  337.         # parse stuff before comma: [filename:]lineno | function
  338.         colon = arg.rfind(':')
  339.         funcname = None
  340.         if colon >= 0:
  341.             filename = arg[:colon].rstrip()
  342.             f = self.lookupmodule(filename)
  343.             if not f:
  344.                 print >>self.stdout, '*** ', repr(filename),
  345.                 print >>self.stdout, 'not found from sys.path'
  346.                 return
  347.             else:
  348.                 filename = f
  349.             arg = arg[colon+1:].lstrip()
  350.             try:
  351.                 lineno = int(arg)
  352.             except ValueError, msg:
  353.                 print >>self.stdout, '*** Bad lineno:', arg
  354.                 return
  355.         else:
  356.             # no colon; can be lineno or function
  357.             try:
  358.                 lineno = int(arg)
  359.             except ValueError:
  360.                 try:
  361.                     func = eval(arg,
  362.                                 self.curframe.f_globals,
  363.                                 self.curframe.f_locals)
  364.                 except:
  365.                     func = arg
  366.                 try:
  367.                     if hasattr(func, 'im_func'):
  368.                         func = func.im_func
  369.                     code = func.func_code
  370.                     #use co_name to identify the bkpt (function names
  371.                     #could be aliased, but co_name is invariant)
  372.                     funcname = code.co_name
  373.                     lineno = code.co_firstlineno
  374.                     filename = code.co_filename
  375.                 except:
  376.                     # last thing to try
  377.                     (ok, filename, ln) = self.lineinfo(arg)
  378.                     if not ok:
  379.                         print >>self.stdout, '*** The specified object',
  380.                         print >>self.stdout, repr(arg),
  381.                         print >>self.stdout, 'is not a function'
  382.                         print >>self.stdout, 'or was not found along sys.path.'
  383.                         return
  384.                     funcname = ok # ok contains a function name
  385.                     lineno = int(ln)
  386.         if not filename:
  387.             filename = self.defaultFile()
  388.         # Check for reasonable breakpoint
  389.         line = self.checkline(filename, lineno)
  390.         if line:
  391.             # now set the break point
  392.             err = self.set_break(filename, line, temporary, cond, funcname)
  393.             if err: print >>self.stdout, '***', err
  394.             else:
  395.                 bp = self.get_breaks(filename, line)[-1]
  396.                 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
  397.                                                                  bp.file,
  398.                                                                  bp.line)
  399.  
  400.     # To be overridden in derived debuggers
  401.     def defaultFile(self):
  402.         """Produce a reasonable default."""
  403.         filename = self.curframe.f_code.co_filename
  404.         if filename == '<string>' and self.mainpyfile:
  405.             filename = self.mainpyfile
  406.         return filename
  407.  
  408.     do_b = do_break
  409.  
  410.     def do_tbreak(self, arg):
  411.         self.do_break(arg, 1)
  412.  
  413.     def lineinfo(self, identifier):
  414.         failed = (None, None, None)
  415.         # Input is identifier, may be in single quotes
  416.         idstring = identifier.split("'")
  417.         if len(idstring) == 1:
  418.             # not in single quotes
  419.             id = idstring[0].strip()
  420.         elif len(idstring) == 3:
  421.             # quoted
  422.             id = idstring[1].strip()
  423.         else:
  424.             return failed
  425.         if id == '': return failed
  426.         parts = id.split('.')
  427.         # Protection for derived debuggers
  428.         if parts[0] == 'self':
  429.             del parts[0]
  430.             if len(parts) == 0:
  431.                 return failed
  432.         # Best first guess at file to look at
  433.         fname = self.defaultFile()
  434.         if len(parts) == 1:
  435.             item = parts[0]
  436.         else:
  437.             # More than one part.
  438.             # First is module, second is method/class
  439.             f = self.lookupmodule(parts[0])
  440.             if f:
  441.                 fname = f
  442.             item = parts[1]
  443.         answer = find_function(item, fname)
  444.         return answer or failed
  445.  
  446.     def checkline(self, filename, lineno):
  447.         """Check whether specified line seems to be executable.
  448.  
  449.         Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
  450.         line or EOF). Warning: testing is not comprehensive.
  451.         """
  452.         line = linecache.getline(filename, lineno, self.curframe.f_globals)
  453.         if not line:
  454.             print >>self.stdout, 'End of file'
  455.             return 0
  456.         line = line.strip()
  457.         # Don't allow setting breakpoint at a blank line
  458.         if (not line or (line[0] == '#') or
  459.              (line[:3] == '"""') or line[:3] == "'''"):
  460.             print >>self.stdout, '*** Blank or comment'
  461.             return 0
  462.         return lineno
  463.  
  464.     def do_enable(self, arg):
  465.         args = arg.split()
  466.         for i in args:
  467.             try:
  468.                 i = int(i)
  469.             except ValueError:
  470.                 print >>self.stdout, 'Breakpoint index %r is not a number' % i
  471.                 continue
  472.  
  473.             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  474.                 print >>self.stdout, 'No breakpoint numbered', i
  475.                 continue
  476.  
  477.             bp = bdb.Breakpoint.bpbynumber[i]
  478.             if bp:
  479.                 bp.enable()
  480.  
  481.     def do_disable(self, arg):
  482.         args = arg.split()
  483.         for i in args:
  484.             try:
  485.                 i = int(i)
  486.             except ValueError:
  487.                 print >>self.stdout, 'Breakpoint index %r is not a number' % i
  488.                 continue
  489.  
  490.             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  491.                 print >>self.stdout, 'No breakpoint numbered', i
  492.                 continue
  493.  
  494.             bp = bdb.Breakpoint.bpbynumber[i]
  495.             if bp:
  496.                 bp.disable()
  497.  
  498.     def do_condition(self, arg):
  499.         # arg is breakpoint number and condition
  500.         args = arg.split(' ', 1)
  501.         try:
  502.             bpnum = int(args[0].strip())
  503.         except ValueError:
  504.             # something went wrong
  505.             print >>self.stdout, \
  506.                 'Breakpoint index %r is not a number' % args[0]
  507.             return
  508.         try:
  509.             cond = args[1]
  510.         except:
  511.             cond = None
  512.         try:
  513.             bp = bdb.Breakpoint.bpbynumber[bpnum]
  514.         except IndexError:
  515.             print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
  516.             return
  517.         if bp:
  518.             bp.cond = cond
  519.             if not cond:
  520.                 print >>self.stdout, 'Breakpoint', bpnum,
  521.                 print >>self.stdout, 'is now unconditional.'
  522.  
  523.     def do_ignore(self,arg):
  524.         """arg is bp number followed by ignore count."""
  525.         args = arg.split()
  526.         try:
  527.             bpnum = int(args[0].strip())
  528.         except ValueError:
  529.             # something went wrong
  530.             print >>self.stdout, \
  531.                 'Breakpoint index %r is not a number' % args[0]
  532.             return
  533.         try:
  534.             count = int(args[1].strip())
  535.         except:
  536.             count = 0
  537.         try:
  538.             bp = bdb.Breakpoint.bpbynumber[bpnum]
  539.         except IndexError:
  540.             print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
  541.             return
  542.         if bp:
  543.             bp.ignore = count
  544.             if count > 0:
  545.                 reply = 'Will ignore next '
  546.                 if count > 1:
  547.                     reply = reply + '%d crossings' % count
  548.                 else:
  549.                     reply = reply + '1 crossing'
  550.                 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
  551.             else:
  552.                 print >>self.stdout, 'Will stop next time breakpoint',
  553.                 print >>self.stdout, bpnum, 'is reached.'
  554.  
  555.     def do_clear(self, arg):
  556.         """Three possibilities, tried in this order:
  557.         clear -> clear all breaks, ask for confirmation
  558.         clear file:lineno -> clear all breaks at file:lineno
  559.         clear bpno bpno ... -> clear breakpoints by number"""
  560.         if not arg:
  561.             try:
  562.                 reply = raw_input('Clear all breaks? ')
  563.             except EOFError:
  564.                 reply = 'no'
  565.             reply = reply.strip().lower()
  566.             if reply in ('y', 'yes'):
  567.                 self.clear_all_breaks()
  568.             return
  569.         if ':' in arg:
  570.             # Make sure it works for "clear C:\foo\bar.py:12"
  571.             i = arg.rfind(':')
  572.             filename = arg[:i]
  573.             arg = arg[i+1:]
  574.             try:
  575.                 lineno = int(arg)
  576.             except ValueError:
  577.                 err = "Invalid line number (%s)" % arg
  578.             else:
  579.                 err = self.clear_break(filename, lineno)
  580.             if err: print >>self.stdout, '***', err
  581.             return
  582.         numberlist = arg.split()
  583.         for i in numberlist:
  584.             try:
  585.                 i = int(i)
  586.             except ValueError:
  587.                 print >>self.stdout, 'Breakpoint index %r is not a number' % i
  588.                 continue
  589.  
  590.             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  591.                 print >>self.stdout, 'No breakpoint numbered', i
  592.                 continue
  593.             err = self.clear_bpbynumber(i)
  594.             if err:
  595.                 print >>self.stdout, '***', err
  596.             else:
  597.                 print >>self.stdout, 'Deleted breakpoint', i
  598.     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  599.  
  600.     def do_where(self, arg):
  601.         self.print_stack_trace()
  602.     do_w = do_where
  603.     do_bt = do_where
  604.  
  605.     def do_up(self, arg):
  606.         if self.curindex == 0:
  607.             print >>self.stdout, '*** Oldest frame'
  608.         else:
  609.             self.curindex = self.curindex - 1
  610.             self.curframe = self.stack[self.curindex][0]
  611.             self.print_stack_entry(self.stack[self.curindex])
  612.             self.lineno = None
  613.     do_u = do_up
  614.  
  615.     def do_down(self, arg):
  616.         if self.curindex + 1 == len(self.stack):
  617.             print >>self.stdout, '*** Newest frame'
  618.         else:
  619.             self.curindex = self.curindex + 1
  620.             self.curframe = self.stack[self.curindex][0]
  621.             self.print_stack_entry(self.stack[self.curindex])
  622.             self.lineno = None
  623.     do_d = do_down
  624.  
  625.     def do_until(self, arg):
  626.         self.set_until(self.curframe)
  627.         return 1
  628.     do_unt = do_until
  629.  
  630.     def do_step(self, arg):
  631.         self.set_step()
  632.         return 1
  633.     do_s = do_step
  634.  
  635.     def do_next(self, arg):
  636.         self.set_next(self.curframe)
  637.         return 1
  638.     do_n = do_next
  639.  
  640.     def do_run(self, arg):
  641.         """Restart program by raising an exception to be caught in the main debugger
  642.         loop. If arguments were given, set them in sys.argv."""
  643.         if arg:
  644.             import shlex
  645.             argv0 = sys.argv[0:1]
  646.             sys.argv = shlex.split(arg)
  647.             sys.argv[:0] = argv0
  648.         raise Restart
  649.  
  650.     do_restart = do_run
  651.  
  652.     def do_return(self, arg):
  653.         self.set_return(self.curframe)
  654.         return 1
  655.     do_r = do_return
  656.  
  657.     def do_continue(self, arg):
  658.         self.set_continue()
  659.         return 1
  660.     do_c = do_cont = do_continue
  661.  
  662.     def do_jump(self, arg):
  663.         if self.curindex + 1 != len(self.stack):
  664.             print >>self.stdout, "*** You can only jump within the bottom frame"
  665.             return
  666.         try:
  667.             arg = int(arg)
  668.         except ValueError:
  669.             print >>self.stdout, "*** The 'jump' command requires a line number."
  670.         else:
  671.             try:
  672.                 # Do the jump, fix up our copy of the stack, and display the
  673.                 # new position
  674.                 self.curframe.f_lineno = arg
  675.                 self.stack[self.curindex] = self.stack[self.curindex][0], arg
  676.                 self.print_stack_entry(self.stack[self.curindex])
  677.             except ValueError, e:
  678.                 print >>self.stdout, '*** Jump failed:', e
  679.     do_j = do_jump
  680.  
  681.     def do_debug(self, arg):
  682.         sys.settrace(None)
  683.         globals = self.curframe.f_globals
  684.         locals = self.curframe.f_locals
  685.         p = Pdb(self.completekey, self.stdin, self.stdout)
  686.         p.prompt = "(%s) " % self.prompt.strip()
  687.         print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
  688.         sys.call_tracing(p.run, (arg, globals, locals))
  689.         print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
  690.         sys.settrace(self.trace_dispatch)
  691.         self.lastcmd = p.lastcmd
  692.  
  693.     def do_quit(self, arg):
  694.         self._user_requested_quit = 1
  695.         self.set_quit()
  696.         return 1
  697.  
  698.     do_q = do_quit
  699.     do_exit = do_quit
  700.  
  701.     def do_EOF(self, arg):
  702.         print >>self.stdout
  703.         self._user_requested_quit = 1
  704.         self.set_quit()
  705.         return 1
  706.  
  707.     def do_args(self, arg):
  708.         f = self.curframe
  709.         co = f.f_code
  710.         dict = f.f_locals
  711.         n = co.co_argcount
  712.         if co.co_flags & 4: n = n+1
  713.         if co.co_flags & 8: n = n+1
  714.         for i in range(n):
  715.             name = co.co_varnames[i]
  716.             print >>self.stdout, name, '=',
  717.             if name in dict: print >>self.stdout, dict[name]
  718.             else: print >>self.stdout, "*** undefined ***"
  719.     do_a = do_args
  720.  
  721.     def do_retval(self, arg):
  722.         if '__return__' in self.curframe.f_locals:
  723.             print >>self.stdout, self.curframe.f_locals['__return__']
  724.         else:
  725.             print >>self.stdout, '*** Not yet returned!'
  726.     do_rv = do_retval
  727.  
  728.     def _getval(self, arg):
  729.         try:
  730.             return eval(arg, self.curframe.f_globals,
  731.                         self.curframe.f_locals)
  732.         except:
  733.             t, v = sys.exc_info()[:2]
  734.             if isinstance(t, str):
  735.                 exc_type_name = t
  736.             else: exc_type_name = t.__name__
  737.             print >>self.stdout, '***', exc_type_name + ':', repr(v)
  738.             raise
  739.  
  740.     def do_p(self, arg):
  741.         try:
  742.             print >>self.stdout, repr(self._getval(arg))
  743.         except:
  744.             pass
  745.  
  746.     def do_pp(self, arg):
  747.         try:
  748.             pprint.pprint(self._getval(arg), self.stdout)
  749.         except:
  750.             pass
  751.  
  752.     def do_list(self, arg):
  753.         self.lastcmd = 'list'
  754.         last = None
  755.         if arg:
  756.             try:
  757.                 x = eval(arg, {}, {})
  758.                 if type(x) == type(()):
  759.                     first, last = x
  760.                     first = int(first)
  761.                     last = int(last)
  762.                     if last < first:
  763.                         # Assume it's a count
  764.                         last = first + last
  765.                 else:
  766.                     first = max(1, int(x) - 5)
  767.             except:
  768.                 print >>self.stdout, '*** Error in argument:', repr(arg)
  769.                 return
  770.         elif self.lineno is None:
  771.             first = max(1, self.curframe.f_lineno - 5)
  772.         else:
  773.             first = self.lineno + 1
  774.         if last is None:
  775.             last = first + 10
  776.         filename = self.curframe.f_code.co_filename
  777.         breaklist = self.get_file_breaks(filename)
  778.         try:
  779.             for lineno in range(first, last+1):
  780.                 line = linecache.getline(filename, lineno, self.curframe.f_globals)
  781.                 if not line:
  782.                     print >>self.stdout, '[EOF]'
  783.                     break
  784.                 else:
  785.                     s = repr(lineno).rjust(3)
  786.                     if len(s) < 4: s = s + ' '
  787.                     if lineno in breaklist: s = s + 'B'
  788.                     else: s = s + ' '
  789.                     if lineno == self.curframe.f_lineno:
  790.                         s = s + '->'
  791.                     print >>self.stdout, s + '\t' + line,
  792.                     self.lineno = lineno
  793.         except KeyboardInterrupt:
  794.             pass
  795.     do_l = do_list
  796.  
  797.     def do_whatis(self, arg):
  798.         try:
  799.             value = eval(arg, self.curframe.f_globals,
  800.                             self.curframe.f_locals)
  801.         except:
  802.             t, v = sys.exc_info()[:2]
  803.             if type(t) == type(''):
  804.                 exc_type_name = t
  805.             else: exc_type_name = t.__name__
  806.             print >>self.stdout, '***', exc_type_name + ':', repr(v)
  807.             return
  808.         code = None
  809.         # Is it a function?
  810.         try: code = value.func_code
  811.         except: pass
  812.         if code:
  813.             print >>self.stdout, 'Function', code.co_name
  814.             return
  815.         # Is it an instance method?
  816.         try: code = value.im_func.func_code
  817.         except: pass
  818.         if code:
  819.             print >>self.stdout, 'Method', code.co_name
  820.             return
  821.         # None of the above...
  822.         print >>self.stdout, type(value)
  823.  
  824.     def do_alias(self, arg):
  825.         args = arg.split()
  826.         if len(args) == 0:
  827.             keys = self.aliases.keys()
  828.             keys.sort()
  829.             for alias in keys:
  830.                 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
  831.             return
  832.         if args[0] in self.aliases and len(args) == 1:
  833.             print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
  834.         else:
  835.             self.aliases[args[0]] = ' '.join(args[1:])
  836.  
  837.     def do_unalias(self, arg):
  838.         args = arg.split()
  839.         if len(args) == 0: return
  840.         if args[0] in self.aliases:
  841.             del self.aliases[args[0]]
  842.  
  843.     #list of all the commands making the program resume execution.
  844.     commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
  845.                          'do_quit', 'do_jump']
  846.  
  847.     # Print a traceback starting at the top stack frame.
  848.     # The most recently entered frame is printed last;
  849.     # this is different from dbx and gdb, but consistent with
  850.     # the Python interpreter's stack trace.
  851.     # It is also consistent with the up/down commands (which are
  852.     # compatible with dbx and gdb: up moves towards 'main()'
  853.     # and down moves towards the most recent stack frame).
  854.  
  855.     def print_stack_trace(self):
  856.         try:
  857.             for frame_lineno in self.stack:
  858.                 self.print_stack_entry(frame_lineno)
  859.         except KeyboardInterrupt:
  860.             pass
  861.  
  862.     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  863.         frame, lineno = frame_lineno
  864.         if frame is self.curframe:
  865.             print >>self.stdout, '>',
  866.         else:
  867.             print >>self.stdout, ' ',
  868.         print >>self.stdout, self.format_stack_entry(frame_lineno,
  869.                                                      prompt_prefix)
  870.  
  871.  
  872.     # Help methods (derived from pdb.doc)
  873.  
  874.     def help_help(self):
  875.         self.help_h()
  876.  
  877.     def help_h(self):
  878.         print >>self.stdout, """h(elp)
  879. Without argument, print the list of available commands.
  880. With a command name as argument, print help about that command
  881. "help pdb" pipes the full documentation file to the $PAGER
  882. "help exec" gives help on the ! command"""
  883.  
  884.     def help_where(self):
  885.         self.help_w()
  886.  
  887.     def help_w(self):
  888.         print >>self.stdout, """w(here)
  889. Print a stack trace, with the most recent frame at the bottom.
  890. An arrow indicates the "current frame", which determines the
  891. context of most commands.  'bt' is an alias for this command."""
  892.  
  893.     help_bt = help_w
  894.  
  895.     def help_down(self):
  896.         self.help_d()
  897.  
  898.     def help_d(self):
  899.         print >>self.stdout, """d(own)
  900. Move the current frame one level down in the stack trace
  901. (to a newer frame)."""
  902.  
  903.     def help_up(self):
  904.         self.help_u()
  905.  
  906.     def help_u(self):
  907.         print >>self.stdout, """u(p)
  908. Move the current frame one level up in the stack trace
  909. (to an older frame)."""
  910.  
  911.     def help_break(self):
  912.         self.help_b()
  913.  
  914.     def help_b(self):
  915.         print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
  916. With a line number argument, set a break there in the current
  917. file.  With a function name, set a break at first executable line
  918. of that function.  Without argument, list all breaks.  If a second
  919. argument is present, it is a string specifying an expression
  920. which must evaluate to true before the breakpoint is honored.
  921.  
  922. The line number may be prefixed with a filename and a colon,
  923. to specify a breakpoint in another file (probably one that
  924. hasn't been loaded yet).  The file is searched for on sys.path;
  925. the .py suffix may be omitted."""
  926.  
  927.     def help_clear(self):
  928.         self.help_cl()
  929.  
  930.     def help_cl(self):
  931.         print >>self.stdout, "cl(ear) filename:lineno"
  932.         print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
  933. With a space separated list of breakpoint numbers, clear
  934. those breakpoints.  Without argument, clear all breaks (but
  935. first ask confirmation).  With a filename:lineno argument,
  936. clear all breaks at that line in that file.
  937.  
  938. Note that the argument is different from previous versions of
  939. the debugger (in python distributions 1.5.1 and before) where
  940. a linenumber was used instead of either filename:lineno or
  941. breakpoint numbers."""
  942.  
  943.     def help_tbreak(self):
  944.         print >>self.stdout, """tbreak  same arguments as break, but breakpoint is
  945. removed when first hit."""
  946.  
  947.     def help_enable(self):
  948.         print >>self.stdout, """enable bpnumber [bpnumber ...]
  949. Enables the breakpoints given as a space separated list of
  950. bp numbers."""
  951.  
  952.     def help_disable(self):
  953.         print >>self.stdout, """disable bpnumber [bpnumber ...]
  954. Disables the breakpoints given as a space separated list of
  955. bp numbers."""
  956.  
  957.     def help_ignore(self):
  958.         print >>self.stdout, """ignore bpnumber count
  959. Sets the ignore count for the given breakpoint number.  A breakpoint
  960. becomes active when the ignore count is zero.  When non-zero, the
  961. count is decremented each time the breakpoint is reached and the
  962. breakpoint is not disabled and any associated condition evaluates
  963. to true."""
  964.  
  965.     def help_condition(self):
  966.         print >>self.stdout, """condition bpnumber str_condition
  967. str_condition is a string specifying an expression which
  968. must evaluate to true before the breakpoint is honored.
  969. If str_condition is absent, any existing condition is removed;
  970. i.e., the breakpoint is made unconditional."""
  971.  
  972.     def help_step(self):
  973.         self.help_s()
  974.  
  975.     def help_s(self):
  976.         print >>self.stdout, """s(tep)
  977. Execute the current line, stop at the first possible occasion
  978. (either in a function that is called or in the current function)."""
  979.  
  980.     def help_until(self):
  981.         self.help_unt()
  982.  
  983.     def help_unt(self):
  984.         print """unt(il)
  985. Continue execution until the line with a number greater than the current
  986. one is reached or until the current frame returns"""
  987.  
  988.     def help_next(self):
  989.         self.help_n()
  990.  
  991.     def help_n(self):
  992.         print >>self.stdout, """n(ext)
  993. Continue execution until the next line in the current function
  994. is reached or it returns."""
  995.  
  996.     def help_return(self):
  997.         self.help_r()
  998.  
  999.     def help_r(self):
  1000.         print >>self.stdout, """r(eturn)
  1001. Continue execution until the current function returns."""
  1002.  
  1003.     def help_continue(self):
  1004.         self.help_c()
  1005.  
  1006.     def help_cont(self):
  1007.         self.help_c()
  1008.  
  1009.     def help_c(self):
  1010.         print >>self.stdout, """c(ont(inue))
  1011. Continue execution, only stop when a breakpoint is encountered."""
  1012.  
  1013.     def help_jump(self):
  1014.         self.help_j()
  1015.  
  1016.     def help_j(self):
  1017.         print >>self.stdout, """j(ump) lineno
  1018. Set the next line that will be executed."""
  1019.  
  1020.     def help_debug(self):
  1021.         print >>self.stdout, """debug code
  1022. Enter a recursive debugger that steps through the code argument
  1023. (which is an arbitrary expression or statement to be executed
  1024. in the current environment)."""
  1025.  
  1026.     def help_list(self):
  1027.         self.help_l()
  1028.  
  1029.     def help_l(self):
  1030.         print >>self.stdout, """l(ist) [first [,last]]
  1031. List source code for the current file.
  1032. Without arguments, list 11 lines around the current line
  1033. or continue the previous listing.
  1034. With one argument, list 11 lines starting at that line.
  1035. With two arguments, list the given range;
  1036. if the second argument is less than the first, it is a count."""
  1037.  
  1038.     def help_args(self):
  1039.         self.help_a()
  1040.  
  1041.     def help_a(self):
  1042.         print >>self.stdout, """a(rgs)
  1043. Print the arguments of the current function."""
  1044.  
  1045.     def help_p(self):
  1046.         print >>self.stdout, """p expression
  1047. Print the value of the expression."""
  1048.  
  1049.     def help_pp(self):
  1050.         print >>self.stdout, """pp expression
  1051. Pretty-print the value of the expression."""
  1052.  
  1053.     def help_exec(self):
  1054.         print >>self.stdout, """(!) statement
  1055. Execute the (one-line) statement in the context of
  1056. the current stack frame.
  1057. The exclamation point can be omitted unless the first word
  1058. of the statement resembles a debugger command.
  1059. To assign to a global variable you must always prefix the
  1060. command with a 'global' command, e.g.:
  1061. (Pdb) global list_options; list_options = ['-l']
  1062. (Pdb)"""
  1063.  
  1064.     def help_run(self):
  1065.         print """run [args...]
  1066. Restart the debugged python program. If a string is supplied, it is
  1067. splitted with "shlex" and the result is used as the new sys.argv.
  1068. History, breakpoints, actions and debugger options are preserved.
  1069. "restart" is an alias for "run"."""
  1070.  
  1071.     help_restart = help_run
  1072.  
  1073.     def help_quit(self):
  1074.         self.help_q()
  1075.  
  1076.     def help_q(self):
  1077.         print >>self.stdout, """q(uit) or exit - Quit from the debugger.
  1078. The program being executed is aborted."""
  1079.  
  1080.     help_exit = help_q
  1081.  
  1082.     def help_whatis(self):
  1083.         print >>self.stdout, """whatis arg
  1084. Prints the type of the argument."""
  1085.  
  1086.     def help_EOF(self):
  1087.         print >>self.stdout, """EOF
  1088. Handles the receipt of EOF as a command."""
  1089.  
  1090.     def help_alias(self):
  1091.         print >>self.stdout, """alias [name [command [parameter parameter ...] ]]
  1092. Creates an alias called 'name' the executes 'command'.  The command
  1093. must *not* be enclosed in quotes.  Replaceable parameters are
  1094. indicated by %1, %2, and so on, while %* is replaced by all the
  1095. parameters.  If no command is given, the current alias for name
  1096. is shown. If no name is given, all aliases are listed.
  1097.  
  1098. Aliases may be nested and can contain anything that can be
  1099. legally typed at the pdb prompt.  Note!  You *can* override
  1100. internal pdb commands with aliases!  Those internal commands
  1101. are then hidden until the alias is removed.  Aliasing is recursively
  1102. applied to the first word of the command line; all other words
  1103. in the line are left alone.
  1104.  
  1105. Some useful aliases (especially when placed in the .pdbrc file) are:
  1106.  
  1107. #Print instance variables (usage "pi classInst")
  1108. alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
  1109.  
  1110. #Print instance variables in self
  1111. alias ps pi self
  1112. """
  1113.  
  1114.     def help_unalias(self):
  1115.         print >>self.stdout, """unalias name
  1116. Deletes the specified alias."""
  1117.  
  1118.     def help_commands(self):
  1119.         print >>self.stdout, """commands [bpnumber]
  1120. (com) ...
  1121. (com) end
  1122. (Pdb)
  1123.  
  1124. Specify a list of commands for breakpoint number bpnumber.  The
  1125. commands themselves appear on the following lines.  Type a line
  1126. containing just 'end' to terminate the commands.
  1127.  
  1128. To remove all commands from a breakpoint, type commands and
  1129. follow it immediately with  end; that is, give no commands.
  1130.  
  1131. With no bpnumber argument, commands refers to the last
  1132. breakpoint set.
  1133.  
  1134. You can use breakpoint commands to start your program up again.
  1135. Simply use the continue command, or step, or any other
  1136. command that resumes execution.
  1137.  
  1138. Specifying any command resuming execution (currently continue,
  1139. step, next, return, jump, quit and their abbreviations) terminates
  1140. the command list (as if that command was immediately followed by end).
  1141. This is because any time you resume execution
  1142. (even with a simple next or step), you may encounter
  1143. another breakpoint--which could have its own command list, leading to
  1144. ambiguities about which list to execute.
  1145.  
  1146.    If you use the 'silent' command in the command list, the
  1147. usual message about stopping at a breakpoint is not printed.  This may
  1148. be desirable for breakpoints that are to print a specific message and
  1149. then continue.  If none of the other commands print anything, you
  1150. see no sign that the breakpoint was reached.
  1151. """
  1152.  
  1153.     def help_pdb(self):
  1154.         help()
  1155.  
  1156.     def lookupmodule(self, filename):
  1157.         """Helper function for break/clear parsing -- may be overridden.
  1158.  
  1159.         lookupmodule() translates (possibly incomplete) file or module name
  1160.         into an absolute file name.
  1161.         """
  1162.         if os.path.isabs(filename) and  os.path.exists(filename):
  1163.             return filename
  1164.         f = os.path.join(sys.path[0], filename)
  1165.         if  os.path.exists(f) and self.canonic(f) == self.mainpyfile:
  1166.             return f
  1167.         root, ext = os.path.splitext(filename)
  1168.         if ext == '':
  1169.             filename = filename + '.py'
  1170.         if os.path.isabs(filename):
  1171.             return filename
  1172.         for dirname in sys.path:
  1173.             while os.path.islink(dirname):
  1174.                 dirname = os.readlink(dirname)
  1175.             fullname = os.path.join(dirname, filename)
  1176.             if os.path.exists(fullname):
  1177.                 return fullname
  1178.         return None
  1179.  
  1180.     def _runscript(self, filename):
  1181.         # The script has to run in __main__ namespace (or imports from
  1182.         # __main__ will break).
  1183.         #
  1184.         # So we clear up the __main__ and set several special variables
  1185.         # (this gets rid of pdb's globals and cleans old variables on restarts).
  1186.         import __main__
  1187.         __main__.__dict__.clear()
  1188.         __main__.__dict__.update({"__name__"    : "__main__",
  1189.                                   "__file__"    : filename,
  1190.                                   "__builtins__": __builtins__,
  1191.                                  })
  1192.  
  1193.         # When bdb sets tracing, a number of call and line events happens
  1194.         # BEFORE debugger even reaches user's code (and the exact sequence of
  1195.         # events depends on python version). So we take special measures to
  1196.         # avoid stopping before we reach the main script (see user_line and
  1197.         # user_call for details).
  1198.         self._wait_for_mainpyfile = 1
  1199.         self.mainpyfile = self.canonic(filename)
  1200.         self._user_requested_quit = 0
  1201.         statement = 'execfile( "%s")' % filename
  1202.         self.run(statement)
  1203.  
  1204. # Simplified interface
  1205.  
  1206. def run(statement, globals=None, locals=None):
  1207.     Pdb().run(statement, globals, locals)
  1208.  
  1209. def runeval(expression, globals=None, locals=None):
  1210.     return Pdb().runeval(expression, globals, locals)
  1211.  
  1212. def runctx(statement, globals, locals):
  1213.     # B/W compatibility
  1214.     run(statement, globals, locals)
  1215.  
  1216. def runcall(*args, **kwds):
  1217.     return Pdb().runcall(*args, **kwds)
  1218.  
  1219. def set_trace():
  1220.     Pdb().set_trace(sys._getframe().f_back)
  1221.  
  1222. # Post-Mortem interface
  1223.  
  1224. def post_mortem(t=None):
  1225.     # handling the default
  1226.     if t is None:
  1227.         # sys.exc_info() returns (type, value, traceback) if an exception is
  1228.         # being handled, otherwise it returns None
  1229.         t = sys.exc_info()[2]
  1230.         if t is None:
  1231.             raise ValueError("A valid traceback must be passed if no "
  1232.                                                "exception is being handled")
  1233.  
  1234.     p = Pdb()
  1235.     p.reset()
  1236.     p.interaction(None, t)
  1237.  
  1238. def pm():
  1239.     post_mortem(sys.last_traceback)
  1240.  
  1241.  
  1242. # Main program for testing
  1243.  
  1244. TESTCMD = 'import x; x.main()'
  1245.  
  1246. def test():
  1247.     run(TESTCMD)
  1248.  
  1249. # print help
  1250. def help():
  1251.     for dirname in sys.path:
  1252.         fullname = os.path.join(dirname, 'pdb.doc')
  1253.         if os.path.exists(fullname):
  1254.             sts = os.system('${PAGER-more} '+fullname)
  1255.             if sts: print '*** Pager exit status:', sts
  1256.             break
  1257.     else:
  1258.         print 'Sorry, can\'t find the help file "pdb.doc"',
  1259.         print 'along the Python search path'
  1260.  
  1261. def main():
  1262.     if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
  1263.         print "usage: pdb.py scriptfile [arg] ..."
  1264.         sys.exit(2)
  1265.  
  1266.     mainpyfile =  sys.argv[1]     # Get script filename
  1267.     if not os.path.exists(mainpyfile):
  1268.         print 'Error:', mainpyfile, 'does not exist'
  1269.         sys.exit(1)
  1270.  
  1271.     del sys.argv[0]         # Hide "pdb.py" from argument list
  1272.  
  1273.     # Replace pdb's dir with script's dir in front of module search path.
  1274.     sys.path[0] = os.path.dirname(mainpyfile)
  1275.  
  1276.     # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
  1277.     # modified by the script being debugged. It's a bad idea when it was
  1278.     # changed by the user from the command line. There is a "restart" command which
  1279.     # allows explicit specification of command line arguments.
  1280.     pdb = Pdb()
  1281.     while 1:
  1282.         try:
  1283.             pdb._runscript(mainpyfile)
  1284.             if pdb._user_requested_quit:
  1285.                 break
  1286.             print "The program finished and will be restarted"
  1287.         except Restart:
  1288.             print "Restarting", mainpyfile, "with arguments:"
  1289.             print "\t" + " ".join(sys.argv[1:])
  1290.         except SystemExit:
  1291.             # In most cases SystemExit does not warrant a post-mortem session.
  1292.             print "The program exited via sys.exit(). Exit status: ",
  1293.             print sys.exc_info()[1]
  1294.         except:
  1295.             traceback.print_exc()
  1296.             print "Uncaught exception. Entering post mortem debugging"
  1297.             print "Running 'cont' or 'step' will restart the program"
  1298.             t = sys.exc_info()[2]
  1299.             pdb.interaction(None, t)
  1300.             print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
  1301.  
  1302.  
  1303. # When invoked as main program, invoke the debugger on a script
  1304. if __name__ == '__main__':
  1305.     import pdb
  1306.     pdb.main()
  1307.